package com.edgar.download.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.edgar.download.R;
import com.edgar.download.Constant;
import com.edgar.download.Download;
import com.edgar.download.DownloadManager;
import com.edgar.download.IDownloadListener;
import com.edgar.download.StatusHelp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by xiexiang on 2015/11/3.
 */
public class AppListActivity extends Activity implements IDownloadListener,AbsListView.OnScrollListener{

    private boolean mScrolling;
    private ListView mListView;
    private DownloadManager mDownloadManager;
    private StatusHelp mStatusHelp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_list);
        mDownloadManager = DownloadManager.getInstance();
        mListView = (ListView) findViewById(R.id.app_listview);
        mListView.setOnScrollListener(this);
        AppListAdapter appListAdapter = new AppListAdapter(this);
        appListAdapter.add(AppDataList.getAppInfoList());
        mListView.setAdapter(appListAdapter);
        mStatusHelp = new StatusHelp(this);
        mListView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
    }

    private void showDialog(){
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_download, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onStart(String url) {
        TextView btnDownload = findDownloadItemButton(url);
        if(btnDownload != null){
            btnDownload.setText("暂停");
        }
    }

    @Override
    public void onPause(String url) {
        TextView btnDownload = findDownloadItemButton(url);
        if(btnDownload != null){
            btnDownload.setText("继续");
        }
    }

    @Override
    public void onCancel(String url) {

    }

    @Override
    public void onFailure(String url,int failStatusCode) {
        TextView btnDownload = findDownloadItemButton(url);
        if(btnDownload != null){
            btnDownload.setText("继续");
        }
    }

    @Override
    public void onComplete(String url) {
        if(mScrolling){
            return;
        }
        View view = mListView.findViewWithTag(url);
        if(view == null)return;
        TextView btnDownload = (TextView) view.findViewById(R.id.app_download);
        btnDownload.setText("下载完成");
    }

    @Override
    public void onWaitDownload(String url){
        TextView btnDownload = findDownloadItemButton(url);
        if(btnDownload != null){
            btnDownload.setText("等待下载");
        }
    }

    @Override
    public void onDownload(String url, int status, int progress) {
        View view = findDownloadItemView(url);
        if(view == null)return;
        ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.download_progressbar);
        progressBar.setProgress(progress);
    }

    private TextView findDownloadItemButton(String url){
        View view = findDownloadItemView(url);
        if(view != null){
            return (TextView) view.findViewById(R.id.app_download);
        }
        return null;
    }

    private View findDownloadItemView(String url){
        if(mScrolling) return null;
        return mListView.findViewWithTag(url);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        this.mScrolling = scrollState == SCROLL_STATE_TOUCH_SCROLL || scrollState == SCROLL_STATE_FLING;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    protected void onDestroy(){
       super.onDestroy();
       mDownloadManager.unRegisterDownloadListener(null,this);
    }

    private class AppListAdapter extends BaseAdapter{

        private LayoutInflater mLayoutInflater;
        private List<AppInfo> mList = new ArrayList<AppInfo>();

        public AppListAdapter(Context context){
            this.mLayoutInflater = LayoutInflater.from(context);
        }

        public void add(Collection<AppInfo> collection){
            mList.addAll(collection);
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public AppInfo getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            AppInfo appInfo = getItem(position);
            ViewHolder viewHolder = null;
            if(convertView == null){
                convertView = mLayoutInflater.inflate(R.layout.app_list_item,null);
                viewHolder = new ViewHolder();
                viewHolder.mAppName = (TextView) convertView.findViewById(R.id.app_name);
                viewHolder.mDownloadProgress = (ProgressBar) convertView.findViewById(R.id.download_progressbar);
                viewHolder.mDownload = (TextView) convertView.findViewById(R.id.app_download);
                convertView.setTag(R.id.item_layout,viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag(R.id.item_layout);
            }
            convertView.setTag(appInfo.getAppDownloadUrl());
            Download download = mDownloadManager.findDownloadByUrl(appInfo.getAppDownloadUrl());
            viewHolder.mAppName.setText(appInfo.getAppName());
            viewHolder.mDownloadProgress.setProgress(download == null ? 0 : download.getProgress());
            viewHolder.mDownload.setTag(appInfo);
            viewHolder.mDownload.setText(mStatusHelp.getDownloadStatusInfo(download));
            viewHolder.mDownload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppInfo appInfoItem = (AppInfo)v.getTag();
                    Download download = mDownloadManager.findDownloadByUrl(appInfoItem.getAppDownloadUrl());
                    if(download == null){
                        download = Download.createDownload(appInfoItem.getAppDownloadUrl(),
                                "",appInfoItem.getAppName()+".apk");
                    }
                    short status = download.getStatus();
                    if(status == Constant.DOWNLOADING){
                        Log.e(Constant.TAG,"start time:"+System.currentTimeMillis());
                        mDownloadManager.pauseDownloadWithDownload(download);
                    } else {
                        mDownloadManager.registerDownloadListener(appInfoItem.getAppDownloadUrl(),
                                AppListActivity.this);
                        mDownloadManager.addDownload(download);
                    }
                }
            });
            return convertView;
        }

        class ViewHolder{
            AppInfo appInfo;
            TextView mAppName;
            ProgressBar mDownloadProgress;
            TextView mDownload;
        }
    }
}